﻿using System;
using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    public class ColorMultiplyFilter : BaseFilter.BaseFilter
    {
        private readonly int[] _bMapping;
        private readonly int[] _gMapping;
        private readonly int[] _rMapping;

        public ColorMultiplyFilter(int r = 0, int g = 0, int b = 0, int density = 0, Func<int, int, int> blend = null, int opacity = 100)
            : base(blend, opacity)
        {
            PrePopulate(ref _rMapping, r, density);
            PrePopulate(ref _gMapping, g, density);
            PrePopulate(ref _bMapping, b, density);
        }

        public override int Process(Rgba rgba)
        {
            rgba.R = _rMapping[rgba.R];
            rgba.G = _gMapping[rgba.G];
            rgba.B = _bMapping[rgba.B];

            return rgba.ToInteger();
        }

        private void PrePopulate(ref int[] mapping, int factor, int density)
        {
            mapping = new int[256];
            float den = density / 100.0f;
            for (int i = 0; i < 256; ++i)
            {
                mapping[i] = Blend(i, MathLibrary.MathLibrary.Clamp((1 - (1 - i / 255.0f) * (1 - factor * den / 255.0f)) * 255.0f));
            }
        }
    }
}